/**   
* @Title: ResourceController.java 
* @Package com.csis.framework.controller 
* @Description: TODO
* @author dailey  
* @date 2012-10-2
* @version V1.0   
*/
package com.csis.system.controller;

import java.awt.Image;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.portlet.ModelAndView;

import com.csis.framework.web.check.Validata;
import com.csis.framework.web.check.paint.ImageFace;
import com.csis.system.common.IStaticData;
import com.csis.system.common.WebUtil;

/**
 * @author dailey
 *
 */
@Controller
@RequestMapping("/resource")
public class ResourceController {

	@Autowired
	private Validata validata;
	@Autowired
	private ImageFace imageFace;

	@RequestMapping("/genValImage")
	public ModelAndView generateValidationImage(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.  
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.  
		response.setHeader("Pragma", "no-cache");
		// return a jpeg  
		response.setContentType("image/jpeg");
		// create the image with the text  
		Image bi = imageFace.createImage(validata);
		// store the text in the session  
		request.getSession().setAttribute(IStaticData.SESSION_VALDATION, validata.getLastCheck());
		ServletOutputStream out = response.getOutputStream();
		// write the data out  
		imageFace.store(bi, out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}

	@RequestMapping("/getImage")
	public void getPicture(@RequestParam String name, HttpServletRequest request, HttpServletResponse response) {
		try {
			byte[] bytes = WebUtil.getImage(request, name);
			response.setDateHeader("Expires", 0);
			// Set standard HTTP/1.1 no-cache headers.  
			response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			// Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
			response.addHeader("Cache-Control", "post-check=0, pre-check=0");
			// Set standard HTTP/1.0 no-cache header.  
			response.setHeader("Pragma", "no-cache");
			// return a icon  
			response.setContentType("image/icon");

			ServletOutputStream out = response.getOutputStream();
			out.write(bytes);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
